import React, { useState } from "react";
import {
  Form,
  Input,
  Button,
  Space, Toast
} from "antd-mobile";
import axios from "axios";
import { useNavigate } from "react-router-dom";
function Login() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const onFinish = (values) => {
    axios.post('/api/login/tel',values).then((res)=>{
      console.log(res)
      if(res.data.code==200){
        const token = res.data.data.token
        localStorage.setItem('token',token)
        navigate('/home')
        Toast.show({
                icon: 'success',
                content: '登录成功',
              })
      }
    })

  };
  const [asd,setAsd] = useState(false)
  const [as,setAs] = useState(60)

  const gettel = ()=>{
    setAsd(true)
    const timer = setInterval(()=>{
      setAs(prev=>{
        if(prev<=1){
          clearInterval(timer)
          setAsd(false)
          return 60
        }
        return prev-1
      })
    },1000)
    const tel = form.getFieldValue('tel');
    axios.get('/api/login/code',{params:{tel}}).then((res)=>{
      console.log(res)
      form.setFieldValue('telCode',res.data.data)
    })

  }

  return (
    <div>
      <Form
      form={form}
      onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Item
          name="tel"
          label="手机号"
          rules={[{ required: true, message: "手机号不能为空" },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入11位数字' }
          ]}
        >
          <Input onChange={console.log} placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item name="telCode" label="短信验证码" extra={<Button onClick={()=>{gettel()}} disabled={asd}>
          {asd?`${as}秒后重新发送`:'获取倒计时'}
          </Button>}>
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
